# -*- coding = utf-8 -*-
# @Time      : 2020/10/14 15:17
# @Author    : Reanon
# @File      : testUrllib.py
# @Email     : dafo360@gmail.com
# @Software  : PyCharm
import socket
import urllib.parse
import urllib.request


def get():
    """
    简单的一个get请求
    :return:
    """
    response = urllib.request.urlopen("http://www.baidu.com")
    # 取回了网页的源代码，并且进行utf-8解码
    print(response.read().decode('utf-8'))


def post():
    """
    模拟浏览器发送一个简单的post请求
    :return:
    """
    # bytes转换为二进制;以utf-8的形式封装字典
    data = bytes(urllib.parse.urlencode({'hello': 'world'}), encoding='utf-8')
    response = urllib.request.urlopen("http://httpbin.org/post", data=data)
    # 接受返回数据，转成utf-8
    print(response.read().decode('utf-8'))


def timeOut():
    """
    使用get请求来测试超时处理
    :return:
    """
    try:
        response = urllib.request.urlopen('http://httpbin.org/get', timeout=4)
        print(response.read().decode('utf-8'))
    except socket.timeout as e:
        print("time out！")


def status1():
    """
    打印出响应类型，状态码、响应头

    :return:
    """
    response = urllib.request.urlopen('http://www.baidu.com')

    # 状态码 判断请求是否成功
    print(response.status)
    # 响应头 得到的一个元组组成的列表
    print(response.getheaders())
    # 得到特定的响应头
    print(response.getheader('Server'))
    # 获取响应体的内容，字节流的数据，需要转成utf-8格式
    print(response.read().decode('utf-8'))


def testRequest(url):
    """
    声明一个request对象，通过这个对象来添加参数
    :return:
    """
    # 测试网址
    # url = "http://httpbin.org/post"
    # 访问豆瓣
    # url = "https://www.douban.com"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36"
    }
    data = bytes(urllib.parse.urlencode({'name': 'eric'}), encoding="utf-8")
    # 包含url,传入数据，响应头，访问方法
    # req = urllib.request.Request(url=url, data=data, headers=headers, method="POST")
    # 可以不用那么多，方法就是get
    req = urllib.request.Request(url=url, headers=headers)
    response = urllib.request.urlopen(req)
    print(response.read().decode("utf-8"))


if __name__ == '__main__':
    # 访问豆瓣
    url = "https://www.douban.com"
    testRequest(url)
